import 'package:flutter/material.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../../entity/home/content/topic_product_entity.dart';
import '../../pages/goods/binding/goods_detail_binding.dart';
import '../../pages/goods/view/goods_detail_page.dart';
import '../../routes/routes.dart';
import '../base/base_image.dart';

class DecorationTopicProduct extends StatelessWidget {
  final TopicProductEntity model;
  const DecorationTopicProduct({
    super.key,
    required this.model,
  });

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return Container(
          width: ScreenUtil().screenWidth,
          decoration: model.bgImage?.attachmentUrl != null && model.bgImage!.attachmentUrl!.isNotEmpty
              ? BoxDecoration(
                  color: Tools.fromHex(model.bgColor ?? '#FFFFFF'),
                  image: DecorationImage(
                    image: NetworkImage(model.bgImage!.attachmentUrl ?? ''),
                    fit: BoxFit.cover,
                  ),
                )
              : BoxDecoration(
                  color: Tools.fromHex(model.bgColor ?? '#FFFFFF'),
                ),
          child: Column(
            children: [
              if (model.showHd!) TopicProductTopView(model: model),
              const SizedBox(height: 8),
              TopicProductBottomView(model: model),
            ],
          ),
        );
      },
    );
  }
}

class TopicProductTopView extends StatelessWidget {
  final TopicProductEntity model;
  const TopicProductTopView({
    super.key,
    required this.model,
  });

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        // 第一部分：背景组件
        SizedBox(
          width: double.infinity, // 适应宽度
          height: ScreenUtil().screenWidth * model.imgTop! / 100.0,
        ),
        // 第二部分：显示的图像
        if (model.hdImage != null && model.hdImage!.attachmentUrl!.isNotEmpty)
          Positioned.fill(
            child: ClipRRect(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(model.bdr!.toDouble()),
                  topRight: Radius.circular(model.bdr!.toDouble()),
                ),
                child: Image.network(model.hdImage!.attachmentUrl!, fit: getBgImageFillStyle())),
          ),
        // 第三部分：上下垂直排列的文本
        Positioned(
          bottom: model.pageMarginTop5!.toDouble(),
          left: model.pageMarginTop5!.toDouble(), // 距离左侧的间距
          right: model.pageMarginTop5!.toDouble(),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(model.bdr5!.toDouble()),
            child: Container(
              color: Tools.fromHex(model.bgColor5!),
              margin: EdgeInsets.only(
                left: model.goodsMarginLeft!.toDouble(),
                bottom: model.goodsMarginTop!.toDouble(),
              ),
              child: Column(
                crossAxisAlignment: crossAxisAlignmentStyle(model.textAlignType2!),
                children: [
                  Text(
                    model.mainText!,
                    textAlign: textAlignmentStyle(model.textAlignType2!),
                    style: TextStyle(
                      color: Tools.fromHex(model.mtitleColor ?? '#FFFFFF'),
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      if (model.link != null) {
                        Tools.jumpPage(model.link!.toJson());
                      }
                    },
                    child: Text(
                      model.subText!,
                      textAlign: textAlignmentStyle(model.textAlignType2!),
                      style: TextStyle(
                        color: Tools.fromHex(model.mtitleColor ?? '#FFFFFF'),
                        fontSize: 16,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  BoxFit getBgImageFillStyle() {
    if (model.imageFillStyle8 == '1') {
      return BoxFit.cover;
    } else if (model.imageFillStyle8 == '2') {
      return BoxFit.contain;
    } else {
      return BoxFit.fill;
    }
  }
}

class TopicProductBottomView extends StatefulWidget {
  final TopicProductEntity model;
  const TopicProductBottomView({
    super.key,
    required this.model,
  });

  @override
  State<TopicProductBottomView> createState() => _TopicProductBottomViewState();
}

class _TopicProductBottomViewState extends State<TopicProductBottomView> {
  @override
  void initState() {
    super.initState();
  }

  double itemWidth() {
    return ScreenUtil().screenWidth * widget.model.per! / 100.0;
  }

  ///获取商品高度
  double itemHeight() {
    switch (widget.model.displayScale) {
      case '0': //3:2
        return itemWidth() * 2 / 3;
      case '2': //3:4
        return itemWidth() * 4 / 3;
      case '3': //16:9
        return itemWidth() * 9 / 16;
      case '1': //1:1
      default:
        return itemWidth();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          height: itemHeight() + 70 + widget.model.pageMarginTop2!.toDouble() / 2 + widget.model.pageMarginBottom!.toDouble(),
          decoration: widget.model.hdImage2?.attachmentUrl != null && widget.model.hdImage2!.attachmentUrl!.isNotEmpty
              ? BoxDecoration(
                  color: Tools.fromHex(widget.model.bgColor2 ?? '#FFFFFF'),
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(widget.model.bdr!.toDouble()),
                    bottomRight: Radius.circular(widget.model.bdr!.toDouble()),
                  ),
                  image: DecorationImage(
                    image: NetworkImage(widget.model.hdImage2!.attachmentUrl ?? ''),
                    fit: BoxFit.cover, // 确保图片按比例填充
                  ),
                )
              : BoxDecoration(
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(widget.model.bdr!.toDouble()),
                    bottomRight: Radius.circular(widget.model.bdr!.toDouble()),
                  ),
                  color: Tools.fromHex(widget.model.bgColor2 ?? '#FFFFFF'),
                ),
        ),
        Container(
          margin: EdgeInsets.only(
            left: widget.model.goodsMarginLeft2!.toDouble() / 2,
            bottom: widget.model.pageMarginBottom2!.toDouble() / 2,
            top: widget.model.pageMarginTop2!.toDouble() / 2,
          ),
          height: itemHeight() + 70,
          child: ListView(
            scrollDirection: Axis.horizontal, // 横向滚动
            children: [
              // 循环添加 ProductCard
              ...widget.model.goods!.map((good) => SizedBox(
                    child: Container(
                      padding: const EdgeInsets.fromLTRB(0, 0, 10, 0),
                      child: ProductCard(styleModel: widget.model, model: good),
                    ),
                  )),
              const SizedBox(width: 10), // 添加间距
              if (widget.model.showMore!) CardMoreInfoView(width: 100, model: widget.model), // “查看更多”视图
            ],
          ),
        ),
      ],
    );
  }
}

class ProductCard extends StatelessWidget {
  final TopicProductEntity styleModel;
  final TopicProductGoods model;
  const ProductCard({super.key, required this.model, required this.styleModel});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        // 处理点击事件，比如导航到商品详情页面
        final id = model.commodityId;
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      child: Container(
        width: itemWidth(),
        height: itemHeight(),
        decoration: BoxDecoration(
          color: _getBackgroundColor(styleModel.sizeType!), //Colors.blue,
          border: _getBorder(styleModel.sizeType!),
          boxShadow: _getBoxShadow(styleModel.sizeType!),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 商品图片
            Stack(children: [
              Image.network(
                model.mainImage != null ? model.mainImage! : '',
                width: itemWidth(),
                height: itemHeight(),
                fit: styleModel.imageFillStyle == '1' ? BoxFit.fill : BoxFit.contain, // 确保图片填充容器
                errorBuilder: (context, error, stackTrace) => const Icon(Icons.error), // 图片加载失败时显示的图标
              ),
              getBadge(),
            ]),
            // 商品名称
            if (styleModel.showTitle == true)
              Align(
                alignment: nameTextAlign(),
                child: Text(
                  model.commodityName!,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 14,
                    color: Tools.fromHex(styleModel.titleColor!),
                    fontWeight: styleModel.textStyleType == '1' ? FontWeight.normal : FontWeight.bold,
                  ),
                ),
              ),
            Container(
              alignment: priceTextAlign(),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  if (styleModel.price == true)
                    Text(
                      '${styleModel.priceQz}${model.price}',
                      style: TextStyle(
                        color: Tools.fromHex(styleModel.priceColor!),
                        fontSize: 14,
                        fontWeight: styleModel.textStyleType == '1' ? FontWeight.normal : FontWeight.bold,
                      ),
                    ),
                  const SizedBox(width: 4),
                  if (styleModel.showOriginPrice == true)
                    Text(
                      '¥${model.priceCost}',
                      style: TextStyle(
                        decoration: TextDecoration.lineThrough,
                        color: Tools.fromHex(styleModel.oldpriceColor!),
                        fontSize: 12,
                      ),
                    ),
                ],
              ),
            ),
            if (styleModel.showSoldNum == true)
              Align(
                alignment: nameTextAlign(),
                child: Text(
                  '已售(${model.number!.toString()})',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.normal,
                    color: Tools.fromHex(styleModel.soldColor!),
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  ///获取角标url
  String getBadgeUrl() {
    switch (styleModel.cornerMarkType) {
      case '1': //热卖
        return 'hot_ch.png';
      case '2': //NEW
        return 'new.png';
      case '3': //HOT
        return 'hot.png';
      case '4': //自定义
        return styleModel.cornerMarkImage!;
      case '0': //新品
      default:
        return 'new_ch.png';
    }
  }

  ///获取角标
  Widget getBadge() {
    return Positioned(
        top: 0,
        left: 0,
        child: Container(
          alignment: Alignment.center,
          child: BaseImage(
            url: getBadgeUrl(),
            width: 32,
            height: 32,
          ),
        ));
  }

  double goodsMargin() {
    var goodsMargin = styleModel.goodsMargin! * 1.0;
    return goodsMargin;
  }

  // text_align_type left center
  Alignment nameTextAlign() {
    return styleModel.textAlignType == 'center' ? Alignment.center : Alignment.centerLeft;
  }

  Alignment priceTextAlign() {
    return styleModel.textAlignType == 'center' ? Alignment.center : Alignment.centerLeft;
  }

  double itemWidth() {
    return ScreenUtil().screenWidth * styleModel.per! / 100.0;
  }

  ///获取商品高度
  double itemHeight() {
    switch (styleModel.displayScale) {
      case '0': //3:2
        return itemWidth() * 2 / 3;
      case '2': //3:4
        return itemWidth() * 4 / 3;
      case '3': //16:9
        return itemWidth() * 9 / 16;
      case '1': //1:1
      default:
        return itemWidth();
    }
  }

  // size_type: '0', //0无边白底 1卡片投影 2描边白底 3无边透明

  // 获取背景颜色
  Color _getBackgroundColor(String sizeType) {
    switch (sizeType) {
      case '0': // 无边白底
      case '2': // 描边白底
        return Colors.white;
      case '3': // 无边透明
        return Colors.transparent;
      case '1': // 卡片投影
        return Colors.white;
      default:
        return Colors.transparent; // 默认透明
    }
  }

  // 获取边框
  Border? _getBorder(String sizeType) {
    switch (sizeType) {
      case '2': // 描边白底
        return Border.all(color: Colors.grey.shade300, width: 1); // 边框样式
      default:
        return null; // 无边框
    }
  }

  // 获取阴影
  List<BoxShadow>? _getBoxShadow(String sizeType) {
    switch (sizeType) {
      case '1': // 卡片投影
        return [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10, // 模糊半径
            spreadRadius: 1, // 阴影扩散
            offset: const Offset(0, 4), // 偏移
          ),
        ];
      default:
        return null; // 无投影
    }
  }
}

class CardMoreInfoView extends StatefulWidget {
  final TopicProductEntity model;
  final double width;

  const CardMoreInfoView({super.key, required this.width, required this.model});

  @override
  State<CardMoreInfoView> createState() => _CardMoreInfoViewState();
}

class _CardMoreInfoViewState extends State<CardMoreInfoView> {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: widget.width,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.0), // 设置圆角
        color: Tools.fromHex('#F2F2F2'), // 设置背景颜色
      ),
      child: Center(
        child: TextButton(
          onPressed: () {
            Map<String, dynamic> json = widget.model.linkMore!.toJson();
            json['link_id'] = int.parse(widget.model.linkMore!.linkId ?? '');
            Tools.jumpPage(json);
          },
          style: TextButton.styleFrom(
            foregroundColor: Tools.fromHex('#7A7A7A'),
            backgroundColor: Colors.transparent, // 背景透明
            shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero), // 去掉边框
          ),
          child: Text(widget.model.moreText!),
        ),
      ),
    );
  }
}

CrossAxisAlignment crossAxisAlignmentStyle(String style) {
  switch (style) {
    case 'left':
      return CrossAxisAlignment.start;
    case 'center':
      return CrossAxisAlignment.center;
    case 'right':
      return CrossAxisAlignment.end;
    default:
      return CrossAxisAlignment.start; // 提供一个默认返回值
  }
}

TextAlign textAlignmentStyle(String style) {
  switch (style) {
    case 'left':
      return TextAlign.start;
    case 'center':
      return TextAlign.center;
    case 'right':
      return TextAlign.end;
    default:
      return TextAlign.start; // 提供一个默认返回值
  }
}
